<template>
  <div class="pad-content-box form-no-padding-box">
    <div>
      <div class="sale-name">基本信息</div>
      <el-form label-width="130px" size="small" ref="searchForm" :model="searchParams">
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="primaryKey" :rules="[{ required: true, message: '请选择', trigger:['change','blur']}]">
              <el-select v-model="searchParams.primaryKey" value-key="primaryKey"  filterable placeholder="请选择" @change="function(item){ return handleChangeSelectId(item)}">
                <el-option
                  v-for="item in agreementList"
                  :key="item.primaryKey"
                  :label="item.contractCode"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商铺名称">
              <el-input placeholder="" v-model="searchParams.rentInfoName" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租户名称">
              <el-input placeholder="" v-model="searchParams.partnerName" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报日期">
              <el-date-picker 
                v-model="searchParams.reportTime" 
                type="date"
                value-format="timestamp"
                placeholder="请选择"> 
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="sale-add">
      <div class="sale-title">销售额上报</div>
      <div class="sale-title-right">
        <div class="add" @click="addSale">新增</div>
      </div>
    </div>
    <el-table class="margin-top-20 has-tab-header-border" empty-text="暂无添加"	 border align="center"  :data="reportInfoList" >
      <el-table-column  label="序号" type="index" width="60"> </el-table-column>
      <el-table-column  label="营业额开始日期" prop="cycleBeginTime" width="170"> 
        <template slot-scope="scope">
          <el-date-picker class="no-border-input yj-input" v-model="scope.row.cycleBeginTime" value-format="timestamp"  type="date" placeholder="选择日期" :class="(!post && !scope.row.cycleBeginTime)?'el-input__inners':''"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column  label="营业额结束日期" prop="cycleEndTime" width="170"> 
        <template slot-scope="scope">
          <el-date-picker class="no-border-input yj-input" v-model="scope.row.cycleEndTime" value-format="timestamp"  type="date" placeholder="选择日期" :class="(!post && !scope.row.cycleEndTime)?'el-input__inners':''"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column  label="销售记录笔数" prop="saleNum">
        <template slot-scope="scope">
          <el-input class="no-border-input yj-input" placeholder="请输入" v-model="scope.row.saleNum" clearable ></el-input>
        </template>
      </el-table-column>
      <el-table-column  label="商品分类" prop="categoryName">
        <template slot-scope="scope">
          <el-input class="no-border-input yj-input" placeholder="请输入" v-model="scope.row.categoryName" clearable></el-input>
        </template>
      </el-table-column>
      <el-table-column  label="税前营业额" prop="operatingAmount"> 
        <template slot-scope="scope">
          <el-input class="no-border-input yj-input" placeholder="请输入" v-model="scope.row.operatingAmount" clearable :class="(!post && !scope.row.operatingAmount)?'el-input__inners':''"></el-input>
        </template>
      </el-table-column>
      <el-table-column  label="税后营业额" prop="afterTaxOperatingAmount"> 
        <template slot-scope="scope">
          <el-input class="no-border-input yj-input" placeholder="请输入" v-model="scope.row.afterTaxOperatingAmount" clearable></el-input>
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="60">
        <template slot-scope="scope">
          <el-button type="text" @click="deleteSale(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="sale-add" style="margin-top:20px;">
      <div class="sale-title">上传文件</div>
      <div class="sale-title-right">
        <div class="add" @click="addFile">添加</div>
      </div>
    </div>
    <div style="margin-top:20px;">
      <el-form label-width="100px" :model="item" ref="fileForm" size="small"  v-for="(item, index) in reportAttachmentList" :key="index">
        <el-row :gutter="50">
          <el-col :span="10">
            <el-form-item label="附件名称" prop="fileTitle" :rules="[{ required: true, message: '请输入', trigger:['change','blur']  }]">
              <el-input placeholder="请输入" v-model="item.fileTitle" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="附件上传" prop="fileUrl" :rules="[{ required:true, message: '请上传附件', trigger: ['change','blur'] }]">
                <uploadFile buttonType="text" isShowList="" :is-multiple="false" :limit="10" filed-name="file" :max-size="70" accept-file-type=".xlsx,.xls,.csv,.png,.jpg,.Png,.Jpg,.docx,.pdf,.zip" @handleSuccess="handleSuccess($event, index, reportAttachmentList)">
                  <template v-slot:info>
                    <div slot="tip" class="margin-left-10 flex align-center">
                      <el-link type="primary" v-if="item.fileUrl" @click="uploadLoad(item.fileUrl)">{{ item.fileDesc }}</el-link>
                      <i class="el-icon-delete el-icon--right color-409EFF" @click.stop="deleteFile(index)"></i>
                    </div>
                  </template>
                </uploadFile>
              </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="dialog-footer">
      <el-button @click="closeDialog({success:false})" size="small" class="el-button-reset">取 消</el-button>
      <el-button type="primary" size="small" @click="save()">确 定</el-button>
    </div>
  </div>
</template>

<script>
  import { saleReprotCreate  ,apiCreateAudit} from '../../../api/salesReport';
  import uploadFile from '@/pages/businessAssets/pages/projectInfo/modules/upload.vue';
  export default {
    name: 'salesReport',
    components:{uploadFile},
    props:{
      agreementList:{
        type:Array,
        default: () => {
          return [];
        },
      }
    },
    data() {
      return {
        searchParams:{},
        reportInfoList:[],
        reportAttachmentList:[],
        validateArr: [],
        total:0,
        post:true
      };
    },
    created() {
    },
    methods: {
      handleChangeSelectId(val){
        this.searchParams.partnerName = val.partnerName
        this.searchParams.rentInfoName = val.rentInfoName
        this.searchParams.contractKey = val.primaryKey
      },
      //添加账单
      addSale(){
        this.reportInfoList.push({})
      },
      //添加附件
      addFile(){
        this.reportAttachmentList.push({
          fileTitle:'',
          fileUrl:''
        })
      },
      deleteFile( index) {
        this.reportAttachmentList.splice(index, 1);
      },
      deleteSale(index){
        this.reportInfoList.splice(index,1)
      },
      //上传成功
      handleSuccess(file, index, list) {
        let num = file.data.rows[0].originalName.lastIndexOf('_');
        let len = file.data.rows[0].originalName.length;
        let cutFileName = file.data.rows[0].originalName.substring(num + 1, len);
        if (file.data.rows && file.data.rows.length > 0) {
          list[index].fileUrl = file.data.rows[0].url;
          list[index].fileId = file.data.rows[0].key;
          list[index].fileDesc = cutFileName;
          this.validateFn();
        } else {
          this.$message.error(file.data.message);
        }
      },
      //校验
      validateFn() {
        this.validateArr = [];
        this.$refs.fileForm[0].validate(valid => {
          if (!valid) {
            this.validateArr.push(1);
          }
        });
        this.$refs.searchForm.validate(valid => {
          if (!valid) {
            this.validateArr.push(1);
          }
        });
      },
      //下载
      uploadLoad(url) {
        let a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      },
      async save() {
        this.post = true
        if(this.reportInfoList.length==0){
          this.$message.error('请新增销售上报明细')
          return
        }else{
          this.reportInfoList.forEach(element => {
            if(!element.cycleBeginTime){
              this.post = false
            }
          });
        }
        if(!this.post){
          return
        }
        this.validateFn()
        if (this.validateArr.length > 0) {
        } else {
          delete this.searchParams.primaryKey
          let res = await saleReprotCreate({
             ...this.searchParams,
             reportAttachmentList:this.reportAttachmentList,
             reportInfoList:this.reportInfoList,
             projectKey:localStorage.getItem('projectKey')
          });
          await apiCreateAudit({
            userPrimaryKey:JSON.parse(localStorage.getItem('userInfo')).key,
            businessKey: res.key, //废止合同保存的主键
            type:'销售额上报',
            typeKey: 'saleReport', //contractSubmit,bill,payment,contractTermination
          })
          this.closeDialog({success:true})
        }
      },
      closeDialog(data){
        this.$emit('closeDialog',data)
        this.searchParams = {}
        this.reportAttachmentList = []
        this.reportInfoList = []
      }
    },
  };
</script>

<style lang="scss" scoped>
  ::v-deep .has-tab-header-border .el-tabs__header {
    border: none;
  }
  .el-input__inners{
    border:1px solid #F56C6C!important;
    border-radius: 5px!important;
  }
  .sale-name{
    font-size: 18px;
    font-weight: bold;
    color: #000;
    padding-bottom: 20px;
  }
  .sale-add{
    display: flex;
    justify-content: space-between;
    margin-top:10px;
    .sale-title{
      font-size: 18px;
      font-weight: bold;
      color: #000;
      height: 30px;
      line-height: 30px;
    }
    .sale-title-right{
      display: flex;
      justify-content: flex-start;
    }
    .add{
      background: #409EFF;
      padding:0 15px;
      color:#fff;
      height: 30px;
      line-height: 30px;
      border-radius: 3px;
      cursor: pointer;
    }
    .cancel{
      margin-left: 10px;
      background: #F56C6C;
      padding:0 15px;
      color:#fff;
      height: 30px;
      line-height: 30px;
      border-radius: 3px;
    }
  }
  .dialog-footer{
    display: flex;
    justify-content: flex-end;
    margin-top:30px;
  }
</style>
